<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="addEmployee">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border>
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{ row }">
              <el-image class="img-container" :src="row.staffPhoto" @click="userInfoStaffPhoto(row.staffPhoto)">
                <template #error>
                  <!-- 静态资源就近维护 -->
                  <img src="@/assets/common/bigUserHeader.png" alt="">
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              {{ _formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{ row }">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" />
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="routerBtn(row.id)">查看</el-button>
              <el-button type="text" size="small" @click="assinrole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delbtn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            @current-change="pageChange"
          />
        </div>
      </el-card>
    </div>
    <add-employee :showdialog="showDialog" @btnshow="btnShow" @btn="btn" />
    <el-dialog title="二维码" :visible="showCodeDialog" @close="showCodeDialog = false">
      <!-- 二维码 -->
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <assign-role
      :show-role-dialog="showRoleDialog"
      :user-id="userId"
      @showRoleDialog="showRoleDialogbtn"
    />
  </div>
</template>

<script>
import { reqGetEmployeeList, delEmployee } from '@/api/employees'
import AddEmployee from './components/add-employee.vue'
import EmployeeEnum from '@/api/constant/employees'
import * as dayjs from 'dayjs'
import { getExportData } from '@/utils/excelData'
import QrCode from 'qrcode'
import AssignRole from './components/assign-role'
export default {
  components: {
    AddEmployee,
    AssignRole
  },

  data() {
    return {
      list: [],
      params: {
        page: 1,
        size: 10
      },
      total: 0,
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  mounted() {
    this.GetEmployeeList()
  },
  methods: {
    async GetEmployeeList() {
      const res = await reqGetEmployeeList(this.params)
      console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    pageChange(page) {
      this.params.page = page
      this.GetEmployeeList()
    },
    // 格式化聘用
    _formatEmployment(type) {
      const hireType = EmployeeEnum.hireType
      // type 1/2
      // {1:'正式', 2:'非正式'}
      // 枚举静态数据 尽量定义成对象  因为对象天生具有一一对应的属性
      const map = {}
      hireType.forEach(item => {
        map[item.id] = item.value
      })
      return map[type]
    },
    // 格式化时间
    formatDate(value, str = 'YYYY-MM-DD') {
      return dayjs(value).format(str)
    },
    // 删除
    delbtn(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEmployee(id)
        this.GetEmployeeList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    addEmployee() {
      this.showDialog = true
    },
    btnShow() {
      this.showDialog = false
    },
    btn() {
      this.GetEmployeeList()
    },
    // 导出
    exportExcel() {
      // 实现导出
      // import 按需导入的语法  router按需导入  只有在正式点击导出按钮之后 这个依赖的文件才会进入到项目
      // 作用就是优化应用打包之后的大小  script-loader

      // import('@/vendor/Export2Excel') -> promise对象 excel 对象 俩个方法 json_excel  table_excel

      // 调用导出方法时的必要参数 (重点关注数据格式)

      // 导出的本质:
      // 1. export2Excel插件  把js数据转化成一个excel表格文件 并且自动触发下载功能完成下载
      // 2. 插件要求的数据从哪里来 如果做处理才能满足条件 需要我们开发人员自行处理
      // 调用接口拿到插件要求的必要数据 如果不满足格式处理好

      import('@/vendor/Export2Excel').then(async excel => {
        console.log(excel)
        // 1.接口调用获取数据
        const res = await reqGetEmployeeList(this.params)
        // 2.处理数据把数据变成插件需要的格式
        const headerRelation = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '工号': 'workNumber',
          '转正日期': 'correctionTime',
          '部门': 'departmentName'
        }
        const { header, data } = getExportData(res.data.rows, headerRelation)
        excel.export_json_to_excel({
          header, // 表头 -> 数组
          data, // 表格主体 -> 二维数组  [[],[],[]]
          filename: '员工列表', // 导出文件的名字
          autoWidth: true, // 内容列的自动宽度
          bookType: 'xlsx' // 文件后缀名 文件类型
        })
      })
    },
    routerBtn(id) {
      this.$router.push({
        path: '/detail',
        query: {
          id
        }
      })
    },
    userInfoStaffPhoto(url) {
      this.showCodeDialog = true
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    // 打开弹框
    assinrole(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    showRoleDialogbtn() {
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.page-tools {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .tips {
    line-height: 34px;
    padding: 0px 15px;
    border-radius: 5px;
    border: 1px solid rgba(145, 213, 255, 1);
    background: rgba(230, 247, 255, 1);
    i {
      margin-right: 10px;
      color: #409eff;
    }
  }
}
.staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
.img-container {
  border-radius: 50%;
  img{
    width: 100%;
  }
}
</style>
